package table_Mixage;


/**
 * Classe pour lecture
 *
 *
 *
 *
 * @author  François Miller/Arnaud Peloux / Damien Deldon</a>
 * @version 1.0
 */

import java.io.*;
import java.util.ArrayList;

public final class MPlayer {

    BufferedOutputStream aos;
    String cmdSox;
    MPlayer() { }
    public boolean lectureFini = true;
    Stop stop;
   
    boolean play(Piste p,Pause pause,Stop stop,ArrayList<PlayerCanal> graph, int debut, int fin){
    	
    	this.stop = stop;

    	lectureFini = false;
    	cmdSox = String.format("play -r %d -c %1d %s -%1d -t raw -",
    			    p.getFrequence(),
    			    p.getNbCanaux(),
    			    p.getSigne() ? "-s" : "", 
    			    p.getResolution());	

    	try{

    	    Process play = Runtime.getRuntime().exec(cmdSox);
    	    aos = new BufferedOutputStream(play.getOutputStream());
    	    int echcour;
    	    int canalcour = 0;
    	    int i = debut;
    	    byte [] buffer;
    	    int resolution = p.getResolution();
    	    p.initLecture();
    	    int nbech = p.getNbEch();
    	    int nbcan = p.getNbCanaux();
    	    while (i < nbech & i< fin){
    			canalcour = 0;
    			
    			int x = debut * 500/nbech;
		    	
    			while (canalcour < p.getNbCanaux()& i < nbech & i< fin){
    				if(!pause.getPause()){
    					echcour = p.getCanal(canalcour).getEchantillon(i);
    					buffer = p.echantillonToByte(echcour,resolution);
    					aos.write(buffer, 0, resolution);
    					canalcour = (canalcour + 1 ) % nbcan;
    					//Dessine la barre de progression
    					if((int)(i% (graph.get(0).graph.m*p.getNbCanaux())) == 0){
    						for (int z = 0; z < p.getNbCanaux();z++){
    							graph.get(z).graph.paintBarre(x++);
    						}
    					}
    					if (canalcour == 0) {
    						i++;
    					}
    					if(stop.getStop()){
        					play.destroy();
    					}
    				}else{
    					Thread.currentThread();
    					Thread.sleep(100);}
    					if(stop.getStop()){
    						play.destroy();
    					}
    				}
    	    }
    	}catch(Exception e){
    	}
    	lectureFini = true;
    	return true;

    }
   
}